package com.hncc.kumao.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ProxySelector;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
import com.github.sardine.ant.command.Exists;
import com.github.sardine.impl.SardineException;
import com.hncc.kumao.entity.BreakpointUploadTask;
import com.hncc.kumao.entity.NetdiskAccessToken;
import com.hncc.kumao.entity.OfflineDownloadTask;
import com.hncc.kumao.exception.KumaoNetdiskFileNotFoundException;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.MyDownloadProgress;
import com.hncc.kumao.util.OfflineDownloadUtils;

public class JianGuoYunOperation {
    
    private static String taskId;

    /**
     * 检查当前网盘信息是否有效
     * @param netdiskAccessToken 网盘信息
     * @return
     */
    public static boolean check(NetdiskAccessToken netdiskAccessToken) {
        try {
            String username = netdiskAccessToken.getUsername();
            String password = netdiskAccessToken.getPassword();
            Sardine sardine = SardineFactory.begin(username, password);
            sardine.list("https://dav.jianguoyun.com/dav/");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    // 进行下载
    public static void download(OfflineDownloadTask offlineDownloadTask, NetdiskAccessToken netdiskAccessToken,
            final MyDownloadProgress progress) throws Exception {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            taskId = offlineDownloadTask.getId();
            
            String username = netdiskAccessToken.getUsername();
            String password = netdiskAccessToken.getPassword();
            Sardine sardine = SardineFactory.begin(username, password);
            
            String downloadUrl = "https://dav.jianguoyun.com/dav" + offlineDownloadTask.getFileUri();
            boolean exists = sardine.exists(downloadUrl);
            System.out.println("是否存在: " + exists);
            if(!exists) {
                System.out.println("未找到该文件");
                throw new KumaoNetdiskFileNotFoundException("未找到该文件");
            }
            inputStream = sardine.get(downloadUrl);
            long contentLength = Long.parseLong(offlineDownloadTask.getFileSize());
            String fileSavePath = offlineDownloadTask.getFileSavePath();
            //创建文件输出流
            if (OfflineDownloadUtils.getTaskProgressState(taskId) == ConstValue.OD_TASK_STATE_GOING) {
                //先创建文件夹，防止文件夹不存在报错
                File tempFile = new File(fileSavePath);
                if (!tempFile.exists()) {
                    if (!tempFile.getParentFile().exists()) {
                        tempFile.getParentFile().mkdirs();
                    }
                }
                fos = new FileOutputStream(fileSavePath);
            }
            byte[] buffer = new byte[4096];
            int r = 0;
            long totalRead = 0;
            if (fos != null) {
                while (((r = inputStream.read(buffer)) > 0)) {
                    if (OfflineDownloadUtils.getTaskProgressState(taskId) != ConstValue.OD_TASK_STATE_GOING) {
                        break;
                    }
                    fos.write(buffer, 0, r);
                    totalRead += r;
                    if (progress != null) {
                        System.out.println(totalRead + "/" + contentLength);
                        progress.onProgress(totalRead, contentLength);
                    }
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

    //上传
    public static void upload(BreakpointUploadTask breakpointUploadTask, NetdiskAccessToken netdiskAccessToken) throws Exception {
        try {
            String username = netdiskAccessToken.getUsername();
            String password = netdiskAccessToken.getPassword();
            Sardine sardine = SardineFactory.begin(username, password);
            
            String uploadUrl = "https://dav.jianguoyun.com/dav" + breakpointUploadTask.getFileUri();
            File uploadFile = new File(breakpointUploadTask.getFileServerPath());
            System.out.println(uploadUrl);
            System.out.println(breakpointUploadTask.getFileServerPath());
            Path path = Paths.get(breakpointUploadTask.getFileServerPath());
            String contentType = Files.probeContentType(path);
            sardine.put(uploadUrl, uploadFile, contentType);
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }
    }
}
